package tomcat.connector;

import tomcat.processor.StaticProcessor;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Connector implements Runnable{
    private static final int DEFAULT_PORT = 8888;

    private ServerSocket server;

    private int port;

    public Connector() {
        this(DEFAULT_PORT);
    }

    public Connector(int port) {
        this.port = port;
    }

    public void start() {
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        try {
            server = new ServerSocket(DEFAULT_PORT);
            System.out.println("Server start Listening " + DEFAULT_PORT);

            while (true) {
                Socket socket = server.accept();
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();

                Request request = new Request(inputStream);
                // 解析请求资源 uri
                request.parse();

                Response response = new Response(outputStream);
                response.setRequest(request);

                if(request.getUri().startsWith("/servlet")) {
                    ServletProcessor processor = new ServletProcessor();
                    // processor.process(request, response);
                }else {
                    StaticProcessor processor = new StaticProcessor();
                    processor.process(request, response);
                }

                // 断开 client 链接
                close(socket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(server);
        }
    }

    private void close(Closeable closable) {
        if (closable != null) {
            try {
                closable.close();
                System.out.println("关闭" + closable);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
